﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Odyssey.Behaviors
{
    public class BindingFocus : DependencyObject
    {



        public static bool GetNotifyOnFocusChanged(DependencyObject obj)
        {
            return (bool)obj.GetValue(NotifyOnFocusChangedProperty);
        }

        public static void SetNotifyOnFocusChanged(DependencyObject obj, bool value)
        {
            obj.SetValue(NotifyOnFocusChangedProperty, value);
        }

        public static readonly DependencyProperty NotifyOnFocusChangedProperty =
            DependencyProperty.RegisterAttached("NotifyOnFocusChanged", typeof(bool), typeof(BindingFocus), new PropertyMetadata(false, OnNotifyOnFocusChanged));

        private static void OnNotifyOnFocusChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)
        {
            bool value = (bool)args.NewValue;
            if (value)
            {
                Control e = (o as Control);
                if (e == null) throw new ArgumentNullException("DependencyObject");
                e.GotFocus += new RoutedEventHandler(OnGotFocus);
                e.LostFocus += new RoutedEventHandler(OnLostFocus);
            }
        }

        

        public static bool GetIsFocused(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsFocusedProperty);
        }

        public static void SetIsFocused(DependencyObject obj, bool value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }

        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(BindingFocus), new PropertyMetadata(false, OnFocusedChanged));


        private static void OnFocusedChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)
        {
            bool newValue = (bool)args.NewValue;
            if (newValue)
            {
                Control e = (o as Control);
                if (e == null) throw new ArgumentNullException("DependencyObject"); 

                if (e != null) e.Focus();
            }

        }

        static void OnLostFocus(object sender, RoutedEventArgs e)
        {
            SetIsFocused(sender as DependencyObject, false);
        }

        static void OnGotFocus(object sender, RoutedEventArgs e)
        {
            SetIsFocused(sender as DependencyObject, true);
        }


    }
}
